// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#include <memory>

#include <nebula/types/type.h>
#include <turbo/base/checked_cast.h>
#include <nebula/util/time.h>

namespace nebula {


namespace util {

// TimestampType -> TimestampType
static const std::pair<DivideOrMultiply, int64_t> kTimestampConversionTable[4][4] = {
    // TimestampType::SECOND
    {{MULTIPLY, 1}, {MULTIPLY, 1000}, {MULTIPLY, 1000000}, {MULTIPLY, 1000000000}},
    // TimestampType::MILLI
    {{DIVIDE, 1000}, {MULTIPLY, 1}, {MULTIPLY, 1000}, {MULTIPLY, 1000000}},
    // TimestampType::MICRO
    {{DIVIDE, 1000000}, {DIVIDE, 1000}, {MULTIPLY, 1}, {MULTIPLY, 1000}},
    // TimestampType::NANO
    {{DIVIDE, 1000000000}, {DIVIDE, 1000000}, {DIVIDE, 1000}, {MULTIPLY, 1}},
};

std::pair<DivideOrMultiply, int64_t> GetTimestampConversion(TimeUnit::type in_unit,
                                                            TimeUnit::type out_unit) {
  return kTimestampConversionTable[static_cast<int>(in_unit)][static_cast<int>(out_unit)];
}

turbo::Result<int64_t> ConvertTimestampValue(const std::shared_ptr<DataType>& in,
                                      const std::shared_ptr<DataType>& out,
                                      int64_t value) {
  auto op_factor =
      GetTimestampConversion(turbo::checked_cast<const TimestampType&>(*in).unit(),
                             turbo::checked_cast<const TimestampType&>(*out).unit());

  auto op = op_factor.first;
  auto factor = op_factor.second;
  switch (op) {
    case MULTIPLY:
      return value * factor;
    case DIVIDE:
      return value / factor;
  }

  // unreachable...
  return 0;
}

}  // namespace util
}  // namespace nebula
